package cn.donting.web.desktop.file.resources.controller;

import cn.donting.file.*;
import cn.donting.file.util.FileUtil;
import cn.donting.web.desktop.file.resources.domain.ResponseEntity;
import cn.donting.web.desktop.file.resources.vo.FileVo;
import cn.donting.web.desktop.sdk.web.user.UserSpace;
import cn.hutool.core.io.IORuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import oshi.PlatformEnum;
import oshi.SystemInfo;
import oshi.driver.windows.wmi.Win32DiskDrive;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.util.FileSystemUtil;
import oshi.util.platform.mac.SysctlUtil;

import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Autowired
    UserSpace userSpace;
    @Autowired
    FileTaskManger taskManger;

    @GetMapping("/userSpace")
    public ResponseEntity<List<FileVo>> getUserSpace() {
        File userSpace = this.userSpace.getUserSpace();
        List<FileVo> fileVos = FileVo.build(userSpace);
        return ResponseEntity.ok(fileVos);
    }

    @GetMapping("/listFile")
    public ResponseEntity<List<FileVo>> listFile(String prentPath) {
        File file = new File(prentPath);
        if (!file.exists()) {
            return ResponseEntity.error("prentPath 不存在：" + prentPath);
        }
        if (file.isFile()) {
            return ResponseEntity.error(file.getPath() + " 不是文件夹!");
        }
        List<FileVo> fileVos = FileVo.build(file);
        return ResponseEntity.ok(fileVos);
    }

    /**
     * 重命名
     *
     * @param filePath
     * @param newName
     * @return
     */
    @PutMapping("/file/rename")
    public ResponseEntity rename(String filePath, String newName) {
        try {
            File file = new File(filePath);
            File newFile = new File(file.getPath() + File.separator + newName);
            file.renameTo(newFile);
            return ResponseEntity.ok(new FileVo(newFile));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseEntity.error(e.getMessage());
        }
    }

    /**
     * 删除文件
     *
     * @param filePath
     * @return
     */
    @DeleteMapping("/files")
    public ResponseEntity files(@RequestBody String[] filePath) throws InterruptedException {
        FileAction fileAction = new FileAction();
        fileAction.setSrcPaths(filePath);
        FileDeleteTask fileDeleteTask = new FileDeleteTask(fileAction);
        fileDeleteTask.start();
        Thread.sleep(800);
        if (fileDeleteTask.getEndTime() != 0) {
            return ResponseEntity.ok("删除成功");
        } else {
            taskManger.push(fileDeleteTask);
            return ResponseEntity.ok(201, fileDeleteTask.getTaskId());
        }

    }

    @PostMapping("/files/move")
    public ResponseEntity filesMove(@RequestBody FileAction fileAction) throws InterruptedException {
        FileMoveTask fileMoveTask = new FileMoveTask(fileAction);
        fileMoveTask.start();
        Thread.sleep(800);
        if (fileMoveTask.getEndTime() != 0) {
            return ResponseEntity.ok("移动成功");
        } else {
            taskManger.push(fileMoveTask);
            return ResponseEntity.ok(201, fileMoveTask.getTaskId());
        }
    }

    @PostMapping("/files/copy")
    public ResponseEntity filesCopy(@RequestBody FileAction fileAction) throws InterruptedException {
        FileCopyTask fileCopyTask = new FileCopyTask(fileAction);
        fileCopyTask.start();
        Thread.sleep(800);
        if (fileCopyTask.getEndTime() != 0) {
            return ResponseEntity.ok("移动成功");
        } else {
            taskManger.push(fileCopyTask);
            return ResponseEntity.ok(201, fileCopyTask.getTaskId());
        }
    }


    /**
     * 创建文件
     *
     * @param name
     * @return
     */
    @PostMapping("/file")
    public ResponseEntity file(String name) {
        File file = new File(userSpace.getDesktop() + File.separator + name);
        if (file.exists()) {
            return ResponseEntity.error("文件以存在");
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return ResponseEntity.error(name + ":文件创建失败");
        }
        return ResponseEntity.ok(null);
    }

    /**
     * 创建文件夹
     *
     * @param name
     * @return
     */
    @PostMapping("/dir")
    public ResponseEntity dir(String name) {
        File file = new File(userSpace.getDesktop() + File.separator + name);
        if (file.exists()) {
            return ResponseEntity.error("文件已存在");
        }
        boolean mkdirs = file.mkdirs();
        return ResponseEntity.ok(mkdirs);
    }


    @GetMapping("/file/task/{taskId}")
    public ResponseEntity fileTask(@PathVariable String taskId) {
        FileTask fileTask = taskManger.getFileTask(taskId);
        return ResponseEntity.ok(fileTask);
    }


    @DeleteMapping("/file/task/{taskId}")
    public ResponseEntity cancel(@PathVariable String taskId) {
        FileTask fileTask = taskManger.getFileTask(taskId);
        fileTask.cancel();
        return ResponseEntity.ok(fileTask);
    }

    @GetMapping("/diskInfo")
    public ResponseEntity<OSFileStore> getDiskInfo() {
        SystemInfo si = new SystemInfo();
        FileSystem fileSystem = si.getOperatingSystem().getFileSystem();
        List<OSFileStore> fileStores = fileSystem.getFileStores();
        return ResponseEntity.ok(fileStores);
    }

    @PostMapping("/uploads")
    public ResponseEntity upload(@RequestParam("file")MultipartFile[] multipartFiles, String prentFilePath) {
        int success=0;
        try {
            File prentFile = new File(prentFilePath);
            for (MultipartFile multipartFile : multipartFiles) {
                String name = multipartFile.getOriginalFilename();
                String targetFileName = FileUtil.fileName(name, prentFile);
                File destFile=new File(prentFile.getPath()+File.separator+targetFileName);
                destFile.createNewFile();
                multipartFile.transferTo(destFile);
                success++;
            }
            return ResponseEntity.ok(null);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
            return ResponseEntity.error("上传失败:成功["+success+"]");
        }
    }

}
